<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <TodoHeader @addList="addList"></TodoHeader>

    <!-- 主体部分 -->
    <TodoBody 
    :list = "renderList" 
    @delBtn="delBtn"
    @changeStatus="changeStatus"></TodoBody>

    <!-- 底部部分 -->
    <TodoFooter v-show="list.length"
     :leaveList="leaveList"
     :isDoneList= "isDoneList"
     :type="type"
     @clearDoneList="clearDoneList"
     @changeType="changeType"></TodoFooter>
  </section>
</template>

<script>
import TodoHeader from '@/components/TodoHeader.vue'
import TodoBody from '@/components/TodoBody.vue'
import TodoFooter from '@/components/TodoFooter.vue'


export default {
  components:{
    TodoHeader,
    TodoBody,
    TodoFooter
  },
  data () {
  return {
    type:'all',
    list: JSON.parse(localStorage.getItem('todoList')) || [ ]
  }
},
// 方法集合
  methods:{
  // 删除事件
  delBtn(id){
    this.list = this.list.filter((item)=>item.id !== id)
  },
  // 添加事件
  addList(caseName){
    const obj = {
      id: +new Date(), name: caseName, isDone: false 
    }
    this.list = [...this.list,obj]
  },
  // 修改状态事件
  changeStatus(id){
   const res =  this.list.find((item)=>item.id === id)
    res.isDone = !res.isDone
  },
  // 清除已完成功能,把未完成的筛选下来
  clearDoneList(){
      this.list =  this.list.filter(item=>item.isDone !== true)
  },
  // 改变状态类型事件
  changeType(type){
      this.type = type
  }
  
},
// 计算属性
  computed:{
    // 计算未完成 剩余功能  完成 true 未完成 false
    leaveList(){
      return  this.list.filter(item=>item.isDone !== true).length
    },
    // 是否显示已完成按钮
    isDoneList(){
      return this.list.some(item => item.isDone === true)
    },
    renderList(){
      if(this.type === 'all'){
        return this.list
      }else  if(this.type === 'active'){
        return this.list.filter(item=>item.isDone !== true)
      }else if(this.type === 'completed'){
        return this.list.filter(item=>item.isDone !== false)
      }else{
        return this.list
      }
    }
   },
   watch:{
    list:{
      deep:true,
      handler(newV){
        // 存本地之前，转JSON
        localStorage.setItem('todoList',JSON.stringify(newV))
      }
    }
   }
}
</script>

<style></style>
